import React, { useCallback, useState, useEffect } from 'react'
import Taro from '@tarojs/taro'
import { Image, View } from '@tarojs/components'
import Images from '@ASSET/Images'
import Modal from '@COMPONENTS/Modal'
import Scenes from '@NAVIGATION/scenes'
import { getStorageSync } from '@UTILS/localStorage'
import { STORAGE_KEY } from '@CONSTANTS/common'
import { trackEvent } from '@UTILS/track/trackUtils'
import style from './LogGuide.module.scss'
const imageArr = [Images.dataCenter.log_guide, Images.dataCenter.log_guide_01]

const LogGuide = () => {
  const [visible, setVisible] = useState(true)
  const [idx, setIdx] = useState(0)
  const contentClassName = `${style.container} ${
    idx === 1 ? style.lastImg : ''
  }`

  const showGuideModal = useCallback(async () => {
    const show = await getStorageSync(STORAGE_KEY.showLogGuideModal)
    setVisible(Boolean(!show))
  }, [])

  const onClickTab = useCallback(
    path => {
      path !== Scenes.dataCenter && showGuideModal()
    },
    [showGuideModal]
  )

  const maskClick = useCallback(() => {
    setIdx(pre => {
      const idx = pre + 1
      trackEvent(idx === 1 ? 'num_log_guide_first' : 'num_log_guide_last')
      if (idx > 1) {
        setVisible(false)
        return pre
      }
      return idx
    })
  }, [])

  useEffect(() => {
    showGuideModal()
    Taro.setStorage({ key: STORAGE_KEY.showLogGuideModal, data: 'false' })
    Taro.eventCenter.on('onClickTab', onClickTab)
    return () => {
      Taro.eventCenter.off('onClickTab', onClickTab)
    }
  }, [showGuideModal, onClickTab])

  return (
    <>
      {visible && (
        <Modal
          visible
          showCancel={false}
          onCancel={maskClick}
          contentClassName={contentClassName}
        >
          <View onClick={maskClick} className={style.imgWarper}>
            {imageArr.map((v, i) => (
              <Image
                key={i}
                mode="widthFix"
                className={style.img}
                src={imageArr[idx]}
                style={{ display: i === idx ? '' : 'none' }}
              />
            ))}
          </View>
        </Modal>
      )}
    </>
  )
}

export default React.memo(LogGuide)
